package com.lovcreate.utils;

import org.apache.poi.xssf.usermodel.*;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/7/29.
 */
public class XlsxDBToExcel {

    public XSSFWorkbook dbToExcel(List<Map<String,String>> list) {
        // 创建一个Excel文档
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
        // 创建一个工作页Sheet
        XSSFSheet xssfSheet = xssfWorkbook.createSheet();
        int rowNums = list.size();
        int colNums = list.get(0).size();
        XSSFRow firstRow = xssfSheet.createRow(0);
        XSSFCell cell;
        String[] keyArr = new String[colNums];
        // 将数据库表的字段名插入
        int count = 0;
        for(String key : list.get(0).keySet()) {
            keyArr[count++] = key;
        }
        for(int i = 0; i < colNums; i++) {
            cell = firstRow.createCell(i);
            cell.setCellValue(new XSSFRichTextString(keyArr[i]));
        }

        for(int i = 0; i < rowNums; i++) {
            XSSFRow row = xssfSheet.createRow(i + 1);
            // 得到要插入的第 i+1 条记录
            Map<String,String> map = list.get(i);
            String[] valueArr = new String[colNums];
            count = 0;
            for(String key : list.get(i).keySet()) {
                valueArr[count++] = map.get(key);
            }
            for(int j = 0; j < colNums; j++) {
                cell = row.createCell(j);
                cell.setCellValue(new XSSFRichTextString(valueArr[j]));
            }
        }
        return xssfWorkbook;
    }
}
